package server

import (
	"core/auth"
	"core/corestruct"
	"core/coreutil"
	"core/myerrors"
	"github.com/gin-gonic/gin"
	"reflect"
	"strings"
)

func GinAction() gin.HandlerFunc {
	return func(c *gin.Context) {

		var url = c.Request.RequestURI
		if index := strings.Index(url, "?"); index > 0 {
			url = url[0:index]
		}
		url = strings.ToLower(url)

		var mact = coreutil.ActionUtil.GetAction(url)
		if mact == nil {
			c.Next()
		} else {
			mycontext, _ := c.Get("MyContext")
			var ctx = mycontext.(*corestruct.HttpContext)

			var hasauth, err = auth.HasAction(mact, ctx)
			if err != nil {

				HttpMsg(ctx, myerrors.ERROR_MSG, "权限错误", err.Error())
				return
			}
			if !hasauth {
				HttpMsg(ctx, myerrors.ERROR_UNAUTHORIZED, "没有权限", "")
				return
			}
			ctx.Act = mact
			varr := make([]reflect.Value, 0)
			if "" == mact.PinType {
				varr = append(varr, reflect.ValueOf(mycontext))

			} else {
				var model = coreutil.StructUtil.Create(mact.PinType)
				//buff := make([]byte, 1024)
				//n, _ := c.Request.Body.Read(buff)
				//var s = string(buff[0:n])
				//fmt.Println(s)
				err := c.ShouldBindJSON(model)
				if err != nil {

					HttpMsg(ctx, myerrors.ERROR_MSG, "json格式错误", err.Error())
					return
				}
				var validmsg = coreutil.Validate(model)
				if "" != validmsg {
					HttpMsg(ctx, myerrors.ERROR_MSG, validmsg, "")
					return
				}
				ctx.Pin = model
				varr = append(varr, reflect.ValueOf(model))
				varr = append(varr, reflect.ValueOf(mycontext))

			}
			dst := mact.Value.Method(0).Call(varr)

			if "" == mact.PoutType {
				if dst[0].Interface() != nil {
					HttpErr(ctx, dst[0].Interface())
					return
				}
				return
			} else {

				if dst[1].Interface() != nil {
					HttpErr(ctx, dst[1].Interface())
					return
				}
			}
			modelout := dst[0].Interface()
			ctx.Pout = modelout
			HttpOK(ctx, modelout)
			AddActoinLog(ctx)
		}

	}
}
